package org.example.echo;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class NettyClientRetry {

    private static final int MAX_TIRES = 2;

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });

        connect(bootstrap, "localhost", 8000, MAX_TIRES);
    }

    private static void connect(final Bootstrap bootstrap, String host, int port, final int retries) {
        bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功!");
            } else if (retries == 0) {
                System.err.println("重试次数已用完，放弃连接！");
                System.exit(1);
            } else {
                int order = (MAX_TIRES - retries) + 1;
                int delay = 1 << order;
                System.err.println(new Date() + ": 连接失败，第" + order + "次重连。。。");
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retries - 1), delay, TimeUnit.SECONDS);
            }

        });
    }
}
